﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ThuVien;

namespace TranTekBE.NhaThuoc
{
    public partial class HistoryTrans : PageRequireLogin
    {
        private string SortBy
        {
            set
            {
                ViewState["SortBy"] = value;
            }
            get
            {
                if (ViewState["SortBy"] != null)
                    return ViewState["SortBy"].ToString();
                return "catShowSeq";
            }
        }

        private string SortDirect
        {
            set
            {
                ViewState["SortDirect"] = value;
            }
            get
            {
                if (ViewState["SortDirect"] != null)
                    return ViewState["SortDirect"].ToString();
                return "ASC";
            }
        }

        private int PageCount
        {
            set
            {
                ViewState["PageCount"] = value;
            }
            get
            {
                return FunctionsUtils.ConvertToInt(ViewState["PageCount"], 1);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Page.Form.DefaultButton = btnSearch.UniqueID;
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "LoadJS", "LoadJS();", true);
            if (Page.IsPostBack == false)
            {
                //txtIDExtra.Text = "9992013007620";
                this.GetListPageSize(ddlPageSize);
                GetInformation();
                

            }


        }

        private void GetInformation()
        {
            if (txtIDExtra.Text.Trim().Length == 0 && txtPhone.Text.Trim().Length == 0)
                return;

            try
            {
                string sql = @" select top 1 C003602 as Ten, C003603 as Ho , C003601 as MaThe , C003605 as SoDt,
		                                      (Select sum(customerAccumulation.C009104)  
		                                      from T0091 customerAccumulation 
		                                      Where customerAccumulation.C009101 = mems.C003600) as DiemTichLuy
      
                                           from T0036 as mems where 1=1" ;
                if (txtIDExtra.Text.Trim().Length > 0)
                    sql += " and C003601 = '" + txtIDExtra.Text.Trim() + "'";
                else
                {
                    if (txtPhone.Text.Trim().Length > 0)
                    {
                        sql += " and C003605 = '" + txtPhone.Text.Trim() + "'";
                    }
                }


                DataSet ds = FunctionsUtils.Database.ExecuteQuery(sql);
                if (!FunctionsUtils.isDataSetNullOrEmpty(ds))
                {
                    lbSoDT.Text = ds.Tables[0].Rows[0]["SoDt"].ToString();
                    lbSoThe.Text = ds.Tables[0].Rows[0]["MaThe"].ToString();
                    lbName.Text = ds.Tables[0].Rows[0]["Ho"].ToString() + " " + ds.Tables[0].Rows[0]["Ten"].ToString();
                    lbExtracare.Text = FunctionsUtils.ConvertMoneyVND(ds.Tables[0].Rows[0]["DiemTichLuy"].ToString());

                    LoadHistoryTransaction();
                }
                else
                    ltError.Text = "Không tìm thấy khách hàng tương ứng";
            }
            catch (Exception ex)
            {

                ltError.Text = ex.Message;
            }
        }

        private void LoadHistoryTransaction()
        {
            //ltError.Text = string.Empty;
            try
            {
                string sSearch = this.CreateSearchCondition();

                //get Total Record de tinh page count
                DataSet ds1 = FunctionsUtils.Database.ExecuteQuery(sSearch);

                int currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);
                int pageSize = FunctionsUtils.ConvertToInt(ddlPageSize.SelectedValue, FunctionsUtils.ConvertToInt(FunctionsUtils.GetConfigValue("PageSize"), 50));
                //int pageCount = FunctionsUtils.PageCount(ds1.Tables[0].Rows.Count, pageSize);
                this.PageCount = FunctionsUtils.PageCount(ds1.Tables[0].Rows.Count, pageSize);
                ds1.Dispose();

                currPage = FunctionsUtils.GetCurrPage(currPage, this.PageCount);
                ltPage.Text = string.Format("&nbsp;{0} of {1}&nbsp;", currPage, this.PageCount);
                txtGoPage.Text = currPage.ToString();

                SetButtonPageNavigationStatus(currPage, this.PageCount);

                //DataSet ds = FunctionsUtils.Database.ExecuteQuery(sSearch);
                DataSet ds = FunctionsUtils.Database.ExecuteQuery(sSearch, currPage, pageSize);

                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    rpCategory.DataSource = ds;
                    rpCategory.DataBind();
                    ltNoRecord.Visible = false;

                    if (this.PageCount == 1)
                    {
                        phPageNavigation.Visible = false;
                    }
                    else
                    {
                        phPageNavigation.Visible = true;
                    }
                }
                else
                {
                    rpCategory.DataSource = null;
                    rpCategory.DataBind();
                    ltNoRecord.Visible = true;
                    phPageNavigation.Visible = false;
                    //ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "NoRC", "HidePageNav();", true);
                }
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                //log.WriteLog("Error in Load Categories: {0} {1}", ex, ex.StackTrace);
            }

            
        }

        private string CreateSearchCondition()
        {
            string where = null;
            if (txtIDExtra.Text.Trim().Length > 0)
                where += " where C003601 = '" + txtIDExtra.Text.Trim() + "'";
            else
            {
                if (txtPhone.Text.Trim().Length > 0)
                {
                    where += " where C003605 = '" + txtPhone.Text.Trim() + "'";
                }
            }



            string sSearch = string.Format(@"Select trans.C002800 as MaBill, trans.UC00001 as NgayBan, trans.c002819 as CuaHang from T0028 trans  
                               Left Join T0019 createUser 
                               on trans.UC00002 = createUser.C001900  
                               Where 
                               trans.C002813 = (select C003600 from T0036 {0} ) ", where);


            if (txtMaBill.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And trans.C002800 like '%{0}%' ", txtMaBill.Text.Trim());
            }

            if (txtCuaHang.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And trans.c002819 like '%{0}%' ", txtCuaHang.Text.Trim());
            }

            if (txtfr.Text.Trim().Length > 0  )
            {
                sSearch += string.Format("And trans.UC00001 >= convert(datetime,'{0} 00:00:00.001') ", txtfr.Text.Trim());

                if(txtto.Text.Trim().Length > 0)
                    sSearch += string.Format("And trans.UC00001 <= convert(datetime,'{0} 23:59:59.999') ", txtto.Text.Trim());
            }

            ////sSearch += string.Format("Order By {0} {1}", this.SortBy, this.SortDirect);
            sSearch += string.Format("Order By {0} {1}", ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue);

            return sSearch;
        }
        private void SetButtonPageNavigationStatus(int currPage, int pageCount)
        {
            if (currPage == 1)
            {
                btnPrev.Enabled = false;
            }
            else
            {
                btnPrev.Enabled = true;
            }

            if (currPage == pageCount)
            {
                btnNext.Enabled = false;
            }
            else
            {
                btnNext.Enabled = true;
            }
        }
        protected void ControlClick_Command(object sender, CommandEventArgs e)
        {
            int currPage = 0;
            switch (e.CommandName)
            {
               
                case "Sort":
                    //remove sort o cac link button khac
                    this.RemoveSortCss();

                    //FunctionsUtils.SelectItemInControlList(ddlSortBy, lbt.CommandName, SelectBy.Value);
                    //FunctionsUtils.SelectItemInControlList(ddlSortDirect, CommandArgument, SelectBy.Value);
                    this.SetSortAtributeForLinkButton(ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue);
                    this. GetInformation();
                    break;
                case "GoToPage":
                    this. GetInformation();
                    break;
                case "GoToPrev":
                    currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);
                    if (currPage > 1)
                    {
                        currPage -= 1;
                    }
                    txtGoPage.Text = currPage.ToString();
                    this. GetInformation();
                    break;
                case "GoToNext":
                    currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);

                    if (currPage < this.PageCount)
                    {
                        currPage += 1;
                    }
                    txtGoPage.Text = currPage.ToString();
                    this.GetInformation();;
                    break;
            }
        }

        protected void Sort_Click(object sender, EventArgs e)
        {
            LinkButton lbt = sender as LinkButton;

            string CommandArgument = string.Empty;
            string css = string.Empty;
            if (lbt.CommandArgument.ToUpper() == "DESC")
            {
                CommandArgument = "ASC";
                css = "sortAsc";
            }
            else
            {
                CommandArgument = "DESC";
                css = "sortDesc";
            }

            //remove sort o cac link button khac
            this.RemoveSortCss();

            lbt.CommandArgument = CommandArgument;
            lbt.CssClass = "GridHeader " + css;
            //this.SortBy = lbt.CommandName;
            //this.SortDirect = CommandArgument;

            FunctionsUtils.SelectItemInControlList(ddlSortBy, lbt.CommandName, SelectBy.Value);
            FunctionsUtils.SelectItemInControlList(ddlSortDirect, CommandArgument, SelectBy.Value);

            GetInformation();
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetInformation();
        }

       

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            GetInformation();
        }

        protected void btnClearSearch_Click(object sender, ImageClickEventArgs e)
        {
            txtfr.Text = null;
            txtto.Text = null;
            txtCuaHang.Text = null;
            txtMaBill.Text = null;
            GetInformation();
        }

        public string formatDate(object date)
        {
            if (date != null)
                return Convert.ToDateTime(date).Date.ToShortDateString() + "<br>" + Convert.ToDateTime(date).ToShortTimeString();
            else
                return null;
        }
    }
}